//
//  WHYUserAccountViewModel.swift
//  WHYWeibo-1.0
//
//  Created by 王洪运 on 15/11/24.
//  Copyright © 2015年 王洪运. All rights reserved.
//

import UIKit

class WHYUserAccountViewModel {
    
    static let sharedUserAccount = WHYUserAccountViewModel()
    
    var avatarURL: NSURL {
        return NSURL(string: userAccount?.avatar_large ?? "")!
    }

    var userAccount: WHYUserAccount?
    
    var userLogon: Bool {
        return (userAccount?.access_token != nil) && !isExpired
    }
    
    private var accountPath: String {
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
        QL2(path)
        return path
    }
    
    private var isExpired: Bool {
        if userAccount?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending
        {
                return false
        }
        return true
    }
    
    typealias WHYIsSuccessedFinishedBlock = (isSuccessed: Bool) -> ()
    
// MARK: - 构造函数
    private init () {
        userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? WHYUserAccount
        
        if isExpired {
            userAccount = nil
        }
    }
}

extension WHYUserAccountViewModel {
    func loadAccessToken (code: String, finished: WHYIsSuccessedFinishedBlock) {
        
        WHYNetWorkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            if error != nil {
                finished(isSuccessed: false)
            }
            
            self.userAccount = WHYUserAccount(dict: result as! [String : AnyObject])
            
            self.loadUserInfo(self.userAccount!, finished: finished)
        }
    }
    
    private func loadUserInfo (account: WHYUserAccount, finished: WHYIsSuccessedFinishedBlock) {
        
        WHYNetWorkTools.sharedTools.loadUserInfo(account.uid!) { (result, error) -> () in
            if error != nil {
                QL4("加载用户出错了")
                finished(isSuccessed: false)
                return
            }
            
            guard let dict = result as? [String: AnyObject] else {
                QL4("格式错误")
                finished(isSuccessed: false)
                return
            }
            
            account.screen_name = dict["screen_name"] as? String
            account.avatar_large = dict["avatar_large"] as? String
            
            NSKeyedArchiver.archiveRootObject(account, toFile: self.accountPath)
            
            finished(isSuccessed: true)
        }
    }
}

